<template>
  <div class="app-container">
    <el-card>
      <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
      >
        <el-form-item label="服务项目">
          <el-input
              v-model="queryParams.name"
              placeholder="请输入服务项目"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="项目类型">
          <el-select
              v-model="queryParams.type"
              clearable
              placeholder="请选择项目类型"
              style="width: 240px"
          >
            <el-option
                v-for="dict in project_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
              v-model="queryParams.status"
              clearable
              placeholder="请选择状态"
              style="width: 240px"
          >
            <el-option
                v-for="dict in contract_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="addDeviceTypes"
          >新增</el-button
          >
        </el-col>

        <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="postList" stripe border max-height="500">
        <el-table-column label="服务项目" align="center" prop="name" />
        <el-table-column label="项目类型" align="center" >
          <template #default="scope">
        <span>
          {{project_type.find(item=>item.value==scope.row.type)? project_type.find(item=>item.value==scope.row.type).label:''}}

        </span>
          </template>
        </el-table-column>
        <el-table-column label="服务内容" align="center" prop="content" show-overflow-tooltip width="500" />

        <el-table-column label="单价（元）" align="center" prop="unitPrice" />
        <el-table-column label="单位" align="center" >
          <template #default="scope">
        <span>
          {{bed_uint.find(item=>item.value==scope.row.unit)? bed_uint.find(item=>item.value==scope.row.unit).label:''}}

        </span>
          </template>
        </el-table-column>
        <el-table-column label="社区管家佣金（元）" align="center" prop="commission" />

        <el-table-column label="状态" align="center">
          <template #default="scope">
            <!-- <span>
              {{contract_status.find(item=>item.value==scope.row.status)? contract_status.find(item=>item.value==scope.row.status).label:''}}
            </span>-->
            <el-tag :type="scope.row.status === '1' ? '':'danger'">
                <span>
               {{contract_status.find(item=>item.value==scope.row.status)? contract_status.find(item=>item.value==scope.row.status).label:''}}
            </span>
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="edit(scope.row)"
            >修改</el-button
            >
            <el-button
                link
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
            >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.page"
          v-model:limit="queryParams.limit"
          @pagination="getList"
      />
    </el-card>
    <el-dialog
        v-model="open"
        :title="title"
        append-to-body
        width="800px"
        v-if="open"
        @close="cancel"
        :close-on-click-modal="false"
    >
      <el-form
          ref="serviceItemRef"
          :model="form"
          :rules="rules"
          label-width="110px"
      >
        <el-form-item label="项目类型" prop="type">
          <el-select
              v-model="form.type"
              clearable
              placeholder="请选择项目类型"
              style="width: 100%"
          >
            <el-option
                v-for="dict in project_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务项目" prop="name">
          <el-input v-model="form.name" placeholder="请输入服务项目" />
        </el-form-item>
        <el-form-item label="单价（元）" prop="unitPrice">
          <el-input v-model="form.unitPrice" placeholder="请输入单价（例如:30.00)" @change="changePrice" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select
              v-model="form.unit"
              clearable
              placeholder="请选择单位"
              style="width: 100%"
          >
            <el-option
                v-for="dict in bed_uint"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="(item, index) in contract_status"
                :key="index"
                :label="item.value"
            >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="服务内容" prop="content">
          <el-input
              v-model="form.content"
              type="textarea"
              show-word-limit
              maxlength="500"
              :autosize="{ minRows: 2, maxRows: 10 }"
              placeholder="请输入服务内容"
          />
        </el-form-item>
        <el-form-item label="社区管家佣金" prop="commission">
          <el-input v-model="form.commission" placeholder="请输入社区管家佣金（例如:5.00)" @change="changCommission" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDebounceHandler"
          >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改岗位对话框 -->
  </div>
</template>

<script setup name="serviceItem">

  const { proxy } = getCurrentInstance();

  const { sys_normal_disable, sys_user_sex, device_category, project_type, contract_status, bed_uint } = proxy.useDict(
      "sys_normal_disable",
      "sys_user_sex",
      "device_category",
      "project_type",
      'contract_status',
      'bed_uint'
  );

  import {
    serviceItem, serviceItemSave, serviceItemUpdata, serviceItemDel
  } from "@/api/homeBed/index"

  import { debounce } from "@/utils/debounce.js"

  import formatNumberWithTwoDecimalPlaces from '@/utils/price-validate'

  const showSearch = ref(true);
  const loading = ref(true);
  const postList = ref([]);
  const open = ref(false);
  const title = ref("新增服务项目");

  const total = ref(0);

  const data = reactive({
    form: {
      status:'1'
    },
    queryParams: {
      page: 1,
      limit: 10,
      status: undefined,
      type:undefined,
      name:undefined
    },
    rules: {
      type: [
        { required: true, message: '请选择项目类型', trigger: 'change' },
      ],
      name: [
        { required: true, message: '请输入服务项目', trigger: 'blur' },
        { min: 0, max: 20, message: '长度不能超过20', trigger: 'blur' },
      ],
      unitPrice: [
        { required: true, message: '请输入单价（元）', trigger: 'blur' },
        { min: 0, max: 8, message: '长度不能超过8', trigger: 'blur' },
      ],
      unit: [
        { required: true, message: '请选择单位', trigger: 'change' },
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' },
      ],
      commission: [
        { min: 0, max: 8, message: '长度不能超过8', trigger: 'blur' },
      ],
      content: [
        { required: false, min: 0, max: 500, message: '服务内容不超过500个字符', trigger: 'blur' }
      ]
    },
  });

  const { queryParams, form, rules } = toRefs(data);

  /**
   * 提交按钮
   */
  const submitFormDebounceHandler = debounce(submitForm, 500);

  function submitForm() {
    proxy.$refs["serviceItemRef"].validate((valid) => {
      if (valid) {
        if (form.value.id != undefined) {
          serviceItemUpdata(form.value).then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            reset();
            getList();
          });
        } else {
          serviceItemSave(form.value).then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            reset();
            getList();
          });
        }
      }
    });
  }

  function cancel() {
    open.value = false;
    reset();
  }

  function edit(data) {
    form.value = data;
    title.value = "编辑服务项目";
    open.value = true;
  }

  function reset() {
      form.value = {
       id: null,
       name:null,
       type:null, unitPrice:null,
      unit:null,
      status:'1',
      content:undefined,
      commission:null,
    };
    proxy.resetForm("serviceItemRef");
  }

  /** 查询岗位列表 */
  function getList() {
    loading.value = true;
    serviceItem(queryParams.value).then((response) => {
      postList.value = response.page.list;
      total.value = response.page.totalCount;
      loading.value = false;
    });
  }

  function handleQuery() {
    getList();
  }

  function resetQuery() {
    queryParams.value = {
      page: 1,
      limit: 10,
      status: undefined,
      type:undefined,
      name:undefined
    };
    getList();
  }

  function handleDelete(row) {
    proxy.$modal
        .confirm("是否确认删除该数据项？")
        .then(function () {
          return serviceItemDel([row.id]);
        })
        .then(() => {
          getList();
          proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
  }

  function addDeviceTypes() {
    title.value = "新增服务项目";
    open.value = true;
  }

  function changCommission(val) {
    if (!(typeof (val - 0) == "number" && !isNaN(val - 0))) {
      proxy.$modal.msgError("请正确输入金额格式");
      form.value.commission = "";
      return false
    }
    form.value.commission=formatNumberWithTwoDecimalPlaces(form.value.commission-0,2)
  }

  function changePrice (val) {
    if (!(typeof (val - 0) == "number" && !isNaN(val - 0))) {
      proxy.$modal.msgError("请正确输入金额格式");
      form.value.unitPrice = "";
      return false
    }
    form.value.unitPrice=formatNumberWithTwoDecimalPlaces(form.value.unitPrice-0,2)
  }

  getList();

</script>
